<?php
class VoteWidget extends Widget {

	public function render($data) {
		//投票列表
		if(intval($data['fieldId']) > 0) {
			if(isset($data['id'])) {
				$map['id']		= $data['id'];
			}else {
				$map['app']		= $data['app'];
				$map['field']	= $data['field'];
				$map['fieldId'] = $data['fieldId'];
				$map['groupId']	= isset($data['groupId']) ? intval($data['groupId']) : 0;
			}
			$res  = M('Vote')->where($map)->order('id DESC')->findPage(10);
			$data = array_merge($data, $res);

			//所有投票的ID
			$data['ids'] = $this->_formatArray($res['data'], 'id');

			$model = M('VoteOpt');
			foreach($data['data'] as $k=>$v) {
				$opts = $model->where("vote_id = {$v['id']}")->order("id ASC")->field("*")->limit('0,2')->findAll();
				$data['data'][$k]['opts'] = $opts;
			}
		}

		$data['groupId'] = isset($data['groupId']) ? $data['groupId'] : 0;
		$data['mid']     = intval($_SESSION['mid']);

		$tpl = isset($data['tpl']) ? $data['tpl'] : 'Vote';
		$content = $this->renderFile("./addons/widgets/".$tpl.".html",$data);
		return $content;
	}

	//将二维数组转换为一维数组
	private function _formatArray($array, $field = 'id') {
		$res = array();
		foreach($array as $v) {
			$res[] = $v[$field];
		}
		return $res;
	}
}
?>